package com.core.sgip.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

import org.apache.log4j.Logger;

import com.core.sgip.client.SGIPClient;
import com.core.sgip.common.SGIPConstant;
import com.core.sgip.common.SGIPMsg;
import com.core.sgip.common.body.command.Bind;
import com.core.sgip.common.body.command.Report;
import com.core.sgip.common.factory.SGIP2UpFactory;
import com.core.sgip.common.factory.SGIPFactory;
import com.core.sgip.common.head.SGIPMsgHead;
import com.core.sgip.interf.SGIPmessageHandler;

public class ConnectHandler implements Runnable {

	private static Logger logger = Logger.getLogger(ConnectHandler.class);

	private Socket socket;

	private SGIPmessageHandler sGIPmessageHandler;

	public ConnectHandler(Socket socket, SGIPmessageHandler sGIPmessageHandler) {
		this.socket = socket;
		this.sGIPmessageHandler = sGIPmessageHandler;
	}

	@Override
	public void run() {
		InetAddress remoteAddress = socket.getInetAddress();
		String remoteIp = remoteAddress.getHostAddress();
		logger.debug("远程连接IP  :" + remoteIp);

		InputStream is = null;
		OutputStream os = null;
		try {
			is = socket.getInputStream();
			os = socket.getOutputStream();

			logger.debug("start receive command bind init...");
			SGIPMsg sgipMsg = SGIP2UpFactory.constructSGIPMsg(SGIPClient.getAvailableBytes(is));
			// 获取客户端传送过来的bind　

			Bind bind = (Bind) sgipMsg.getCommand();
			String appkey = bind.getLoginName();
			String secretKey = bind.getLoginPassWord();

			logger.info("账号：" + appkey);
			logger.info("密码：" + secretKey);

			SGIPMsgHead head = sgipMsg.getHead();
			
			String bindseqNum = head.getSequenceNumberStr();
			System.out.println("----------------------------bindseqNum1            "+bindseqNum);
			
			byte[] dataByte = null;
			logger.debug("start receive command head =" + head);
			if (null != head) {
				logger.debug("start receive command bind do...");
				// 接受到bind
				long commandId = head.getCommandId();
				if (SGIPConstant.SGIP_BIND == commandId) {
					// 响应bindResp
					sgipMsg = SGIP2UpFactory.getSGIPMsg(SGIPConstant.SGIP_BIND_RESP);
					dataByte = sgipMsg.getByteData();
					os.write(dataByte);
					os.flush();
					logger.debug("start receive command bind bindResp...");

					boolean notUnbind = true;
					while (notUnbind) {
						logger.debug("start receive command deliver init...");
						sgipMsg = SGIP2UpFactory.constructSGIPMsg(SGIPClient.getAvailableBytes(is));
						head = sgipMsg.getHead();
						System.out.println("----------------------------bindseqNum2           "+head.getSequenceNumberStr());
						logger.debug("start receive command deliver head =" + head);
						if (null != head) {
							commandId = head.getCommandId();
							/**
							 * ###提供客户下发数据submit
							 */
							
							if (SGIPConstant.SGIP_SUBMIT == commandId) {// 3
								logger.debug("start receive command submit do...");
								// 处理SUBMIT
								sGIPmessageHandler.handleSubmitMessageByClientsend(head, sgipMsg, appkey, secretKey, os);

								logger.debug("start receive command submit submitResp...");
							}
							
							/**
							 * ###提供供应商提供上行数据
							 */
							else if (SGIPConstant.SGIP_DELIVER == commandId) {// 4
								logger.debug("start receive command deliver do...");
								// 处理Delivery
								sGIPmessageHandler.handleDeliverMessageRallbackMO(head, sgipMsg, appkey, secretKey, os);

								sgipMsg = SGIPFactory.getSGIPMsg(SGIPConstant.SGIP_DELIVER_RESP);
								os.write(sgipMsg.getByteData());
								os.flush();
								logger.debug("start receive command deliver deliverResp...");
								
							} 
							/**
							 * ###提供供应商提供状态报告数据
							 */
							else if (SGIPConstant.SGIP_REPORT == commandId) {// 5
								logger.debug("start receive command report do...");
								// 处理report
								sGIPmessageHandler.handleReportMessagePushstate(head, (Report) sgipMsg.getCommand());

								// 响应reportResp
								sgipMsg = SGIPFactory.getSGIPMsg(SGIPConstant.SGIP_REPORT_RESP);
								os.write(sgipMsg.getByteData());
								os.flush();
								logger.debug("start receive command report reportResp...");
								
								//解绑
							} else if (SGIPConstant.SGIP_UNBIND == commandId) {// 2
								logger.debug("start receive command unbind do...");
								notUnbind = false;
								// 响应UnbindResp
								sgipMsg = SGIP2UpFactory.getSGIPMsg(SGIPConstant.SGIP_UNBIND_RESP);
								os.write(sgipMsg.getByteData());
								os.flush();
								logger.debug("start receive command unbind unbindResp...");
							}
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("处理异常.详情：" + e);
			e.printStackTrace();
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != socket) {
				logger.debug("*********release connect socket");
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
	

}
